package ru.zombator.taskman.client.query.corba;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.rmi.RemoteException;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.InvalidName;
import org.omg.CosNaming.NamingContextPackage.NotFound;

import ru.zombator.taskman.core.query.IPacket;
import ru.zombator.taskman.core.query.IResponderCli;
import ru.zombator.taskman.server.query.corba.ICorbaServer;
import ru.zombator.taskman.server.query.corba.ICorbaServerHelper;
import ru.zombator.taskman.server.utils.Base64;

/**
 * CORBA-клиент.
 * <p>
 * В отличие от нормальных клиентов, не передает объекты, а передает
 * строчки (в них base64-закодированные данные). Изврат? Ага.
 * 
 * @author nvamelichev
 *
 */
public class CorbaClient implements IResponderCli {
	private ICorbaServer srvImpl;

	@Override
	public IPacket getResponse(IPacket request) throws RemoteException {
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;

		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(request);
			byte[] reqBytes = baos.toByteArray();
			String reqString = Base64.encode(reqBytes);

			String respString = srvImpl.getResponse(reqString);
			byte[] respBytes = Base64.decode(respString);
			ByteArrayInputStream bais = new ByteArrayInputStream(respBytes);
			ois = new ObjectInputStream(bais);
			return (IPacket) ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RemoteException(e.getMessage(), e);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new RemoteException(e.getMessage(), e);
		} catch (ru.zombator.taskman.server.query.corba.RemoteException e) {
			e.printStackTrace();
			throw new RemoteException(e.message, e);
		}
	}

	public CorbaClient(String serverIp) throws NotFound, CannotProceed,
			InvalidName {
		String[] args = { "-ORBInitialPort", "1550", "-ORBInitialHost",
				serverIp };
		ORB orb = ORB.init(args, null);

		org.omg.CORBA.Object objRef = orb.string_to_object("corbaloc:iiop:"
				+ serverIp + ":1550/NameService");
		NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

		String name = "ICorbaServer";
		srvImpl = ICorbaServerHelper.narrow(ncRef.resolve_str(name));
	}
}
